import com.alibaba.fastjson.JSONObject;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Put;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import util.Util;

import java.io.IOException;
import java.time.Duration;
import java.util.Collections;
import java.util.Properties;

public class Main {

    public static void main(String[] args) throws IOException {

        Properties properties = new Properties();
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,
                "172.17.61.28:9092,172.17.61.29:9092,172.17.61.30:9092");
        //配置从头消费数据
        properties.put("auto.offset.reset", "latest");
        // 制定consumer group
        properties.put("group.id", "naive");
        // 是否自动确认offset
        properties.put("enable.auto.commit", "true");
        // 自动确认offset的时间间隔
        properties.put("auto.commit.interval.ms", "1000");
        // key的序列化类
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG,
                "org.apache.kafka.common.serialization.StringDeserializer");
        // value的序列化类
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,
                "org.apache.kafka.common.serialization.StringDeserializer");
        KafkaConsumer<String, String> consumer = new KafkaConsumer<>(properties);
        consumer.subscribe(Collections.singletonList("my-own-topic"));

        Configuration conf = HBaseConfiguration.create();
        Connection connection = ConnectionFactory.createConnection(conf);

        while (true) {
            ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(100));
            for (ConsumerRecord<String, String> record : records) {
                System.out.println(record.value());
                try {
                    JSONObject jo = JSONObject.parseObject(record.value());
                    String topic = jo.getString("topic");
                    JSONObject rawData = jo.getJSONArray("value").getJSONObject(0);
                    Put[] put = Util.getPut(topic, rawData);
                    if (put == null) {
                        throw new Exception("deep♂dark♂fantasy");
                    }
                    TableName tableName = TableName.valueOf(topic);
                    Util.putTable(connection, tableName, put);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    }

}
